<script lang="ts" setup>
import type { UnwrapRef } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import ExcelJS from 'exceljs';
import quarter_add from './quarter/quarter_add.vue';
import { useUpload } from './useUpload';
import { useQuarterHistoryStore } from '@/store/modules/dcp/assessment_indicators/quarter_history';

const searchkeyword = ref('');
const dataIsReady = ref(false);
const loading = ref<boolean>(false);
const data = ref<any[]>([]);

async function getAllcountryData() {
  data.value = [];
  loading.value = true;
  await getcountyList().then((res: any) => {
    data.value = res.data;
    dataIsReady.value = true;
  }).catch(() => {
    message.error('数据获取失败！');
  })
    .finally(() => {
      loading.value = false;
    });
}
onMounted(async () => {
  getAllcountryData();
});
const allColumns: any = [
  {
    title: '区县网运线季度考核指标',
    children: [
      {
        title: '指标名称',
        dataIndex: 'indicatorName',
        key: 'indicatorName',
        align: 'center',

      },
      {
        title: '分值',
        dataIndex: 'score',
        key: 'score',
        align: 'center',

      },
      {
        title: '县体考核办法',
        dataIndex: 'assessmentMethod',
        key: 'assessmentMethod',
        align: 'center',

      },
      {
        title: '提供人',
        dataIndex: 'provider',
        key: 'provider',
        align: 'center',

      },
    ],
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    align: 'center',
    fixed: 'right',
  },
];
const { auth } = useAuth();
function showRoleColumn() {
  return auth([
    'a_i_exitquota',
  ]);
}
const columns: any = computed(() => {
  return allColumns.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
const visible = ref<boolean>(false);
const editableData: UnwrapRef<Record<string, any>> = reactive({});

// 定义搜索方法
async function onSearch(value: string) {
  if (!value) {
    message.info('请输入搜索关键词');
    return;
  }
  try {
    const res: any = await getcountyDetails(Number.parseInt(value)); // 将字符串转换为数字
    message.success('搜索成功');
    if (res && res.data) {
      data.value = [res.data]; // 假设返回的是单个对象
    }
    else {
      data.value = []; // 如果没有数据，确保 data 是一个空数组
    }
  }
  catch (error) {
    console.error('搜索失败:', error);
    message.error('搜索失败');
    data.value = []; // 确保在搜索失败时 data 是一个空数组
  }
}
// 跳转
function linkObject(record: any) {
  return { name: 'assessmentIndicatorsQuarterDetails', query: { assessmentMethod: record.assessmentMethod } };
}

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}
function add() {
  getVisible();
}
function getVisible() {
  visible.value = !visible.value;
  getAllcountryData();
}
async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  const updateDate = {
    id: newData.id,
    indicatorName: newData.indicatorName,
    score: newData.score,
    assessmentMethod: newData.assessmentMethod,
    provider: newData.provider,
  };
  try {
    await updatecounty(updateDate);
    message.success('修改成功');
  }
  catch (error) {
    console.error('Update failed:', error);
    message.error('修改失败');
  }
  delete editableData[id];
}
function cancel(id: number) {
  delete editableData[id];
}
async function deleteSinglequarter(id: number) {
  await deletecountyDetails(id).then(() => {
    message.success('删除成功！');
    getAllcountryData();
  });
}

async function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      deleteSinglequarter(id);
    },
  });
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      // loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            // 上传到数据库
            await addQuarterPublicSheetFileupload(formData).then(() => {
              message.success('上传成功！');
              // 移除文件
              handleRemove(file);
              // 更新数据
              getAllcountryData();
            })
              .catch(() => {
                message.error('上传失败');
                // 重新更新数据，将原先显示在页面的数据撤回
                getAllcountryData();
              });
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 日期
const datePicker = ref<any>(null);
// function getQuarterNumber(quarterStr: string): number | null {
//   const match = quarterStr.match(/第(\d+)季度/);
//   if (match && match[1]) {
//     return Number.parseInt(match[1], 10);
//   }
//   return null; // 如果没有匹配到，返回 null
// }
function changeTime() {
  nextTick(() => {
    if (datePicker.value) {
      datePicker.value.blur();
    }
  });
}
function getCurrentYearMonth(): string {
  // 获取当前年月
  const now = new Date();
  const year = now.getFullYear();
  return `${year}年`;
}
const year = ref<any>(getCurrentYearMonth());
const yearMonth = ref<any[]>([]);
const date = ref<any[]>([]);
const isdisabled = ref<boolean[]>([false, false, false, false]);
function extractYearAndQuarter(data: any): any {
  const match = data.yearMonth.match(/(\d{4})第(\d)季度/);
  if (match) {
    const [, year, quarter] = match;
    return {
      year: Number.parseInt(year, 10),
      quarter: Number.parseInt(quarter, 10),
    };
  }
  else {
    throw new Error(`Invalid format for yearMonth: ${data.yearMonth}`);
  }
}
async function getYearMonth() {
  await useQuarterHistoryStore().getQuarterList();
  yearMonth.value = useQuarterHistoryStore().quarterList;
  for (let i = 0; i < yearMonth.value.length; i++) {
    const result = extractYearAndQuarter(yearMonth.value[i]);
    date.value.push({ year: `${result?.year}年`, quarter: `第${result?.quarter}季度` });
  }
}

const quarterChoose = ref<string>('第1季度');
function visibleButton(str: string) {
  quarterChoose.value = str;
}
function isCurrentQuarterFinalized(y: any, q: any) {
  for (let i = 0; i < date.value.length; i++) {
    if (date.value[i].year === y.value && q === date.value[i].quarter) {
      return true;
    }
  }
  return false;
}
// 执行定稿操作
async function finalize() {
  const currentYear = year.value.replace(/年/g, '');
  const currentQuarter = quarterChoose.value;

  if (!currentQuarter) {
    message.error('请选择季度！');
    return;
  }

  if (isCurrentQuarterFinalized(year.value, currentQuarter)) {
    message.error('该季度已定稿');
    return;
  }

  if (data.value.length === 0) {
    message.error('没有数据可定稿！');
    return;
  }

  try {
    await Quartercreate(`${currentYear}${currentQuarter}`);
    message.success('定稿成功！');
    data.value = [];
    disabledQuarter(); // 更新季度禁用状态
  }
  catch (error) {
    message.error('定稿失败！');
  }
}

onMounted(async () => {
  await getYearMonth();
  disabledQuarter();
});
watch(year, () => {
  disabledQuarter();
});
function disabledQuarter() {
  isdisabled.value = [false, false, false, false];
  for (let i = 0; i < 4; i++) {
    const quarter = `第${i + 1}季度`;
    for (let j = 0; j < date.value.length; j++) {
      if (date.value[j].year === year.value && quarter === date.value[j].quarter) {
        isdisabled.value[i] = true;
      }
    }
  }
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            区县网运线季度考核指标
          </div>
          <a-button type="link" @click="$router.push('/assessment_indicators/quarter/history')">
            历史记录
          </a-button>
          <a-button type="link" @click="$router.push('/assessment_indicators/quarter/summary')">
            汇总表
          </a-button>
          <a-button v-auth="'a_i_add'" type="link" @click="add">
            新增
          </a-button>
          <a-input-search
            v-model:value="searchkeyword" placeholder="请输入id" enter-button style="width: 200px;"
            @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <div>
            <a-space>
              <a-date-picker
                ref="datePicker" v-model:value="year" picker="year" value-format="YYYY年" format="YYYY年"
                :bordered="false" :allow-clear="false" input-read-only size="small" style="width: 70px;"
                @change="changeTime"
              >
                <template #suffixIcon />
              </a-date-picker>
              <a-dropdown style="color: black;">
                <span class="ant-dropdown-link" @click.prevent>
                  {{ quarterChoose }}
                  <DownOutlined />
                </span>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="1" :disabled="isdisabled[0]">
                      <a :style="{ color: isdisabled[0] ? '#ccc' : 'black' }" @click="visibleButton('第1季度')">第1季度</a>
                    </a-menu-item>
                    <a-menu-item key="2" :disabled="isdisabled[1]">
                      <a :style="{ color: isdisabled[1] ? '#ccc' : 'black' }" @click="visibleButton('第2季度')">第2季度</a>
                    </a-menu-item>
                    <a-menu-item key="3" :disabled="isdisabled[2]">
                      <a :style="{ color: isdisabled[2] ? '#ccc' : 'black' }" @click="visibleButton('第3季度')">第3季度</a>
                    </a-menu-item>
                    <a-menu-item key="4" :disabled="isdisabled[3]">
                      <a :style="{ color: isdisabled[3] ? '#ccc' : 'black' }" @click="visibleButton('第4季度')">第4季度</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </div>
          <a-upload
            v-auth="'e-index-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
            :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-auth="'e-index-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button type="primary" @click="finalize">
            定稿
          </a-button>
        </a-space>
      </div>
      <quarter_add v-if="visible" class="index-add" :visible="visible" :get-visible="getVisible" />
    </div>
    <div class="content">
      <a-table
        :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1200 }" :pagination="false"
        class="m-table" :loading="loading"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="['indicatorName', 'score', 'provider'].includes(column.dataIndex as string)">
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-if="column.dataIndex === 'assessmentMethod'">
            <RouterLink :to="linkObject(record)">
              {{ text }}
            </RouterLink>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-typography-link @click="save(record.id)">保存</a-typography-link>
                <a @click="cancel(record.id)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.id)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .m-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
